package com.ff.neuropp.service;


import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.ff.neuropp.domain.Order;
import com.ff.neuropp.repository.OrderRepository;
import com.ff.neuropp.util.ResultTool;
import com.ff.neuropp.util.SnowIdUtil;

@Service
public class AppOrderService {


    @Resource
    private OrderRepository orderRepository;


    interface ORDER_STATUS{

        int pre = 0;

        int success =1;

        int fail = 2;
    }


    /**
     * 创建预支付订单
     * @return
     */
    public Map<String, Object> createOrder(Order param) {
    	
    	String userId=param.getIosUser().getUserId();//购买人
    	Integer courseId=param.getCourse().getId();//课程Id
    	Order o=orderRepository.findByUserIdAndCourse_id(userId,courseId);
    	if(null!=o) {
    		return ResultTool.genFailResult(ResultTool.ErrorCode_1,"Error,exist bought!");
    	}
    	  //创建订单号
        String orderId = SnowIdUtil.orderId();
        param.setOrderNum(orderId);
        param.setUpdateTime(new Date());
        param.setOrderStatus(ORDER_STATUS.pre);
        param.setUserId(param.getIosUser().getUserId());
        Order order = orderRepository.save(param);
        return ResultTool.genSuccessResult(order);
    }


    /**
     * 更新订单
     * @param param
     * @return
     */
    public Map<String, Object> update(Order param) {
        param.setUpdateTime(new Date());
        Order order = orderRepository.findByOrderNum(param.getOrderNum());
        order.setOrderStatus(param.getOrderStatus());
        order.setUpdateTime(param.getUpdateTime());
        orderRepository.save(order);//更新订单
        return ResultTool.genSuccessResult(order);
    }


    /**
     *  订单查询
     * @param orderNum
     * @return
     */
    public Map<String, Object> query(String orderNum) {
        Order order = orderRepository.findByOrderNum(orderNum);
        if(order!=null){
            return ResultTool.genSuccessResult(order);
        }
        return ResultTool.genFailResult(ResultTool.ErrorCode_1,"未查询到订单信息");
    }
}